using System;
using SimpleJSON;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

namespace Gj
{
    public class AttrFormatHelper : NodeHelper
    {
        public enum Handle
        {
            None,
            RateToSpeed,
            TimeToSpeed
        }

        public Handle handle = Handle.None;
        public Color disableColor = new(255, 255, 255, 0.4f);
        public Color originColor = new(255, 255, 255);
        [SelectRef(UIKey.ATTR_KEY)] public string attrKey;
        [SelectRef(UIKey.ATTR_KEY)] public string attrCountKey;
        public bool pro;
        public string format;

        [SelectRef(UIKey.DATA_KEY)] public SelectKey disabledKey;
        public bool invert;
        private bool _init;
        private string _s;
        private Text _Text;
        private TextMeshProUGUI _TextPro;
        protected bool disabled;

        private Text Text
        {
            get
            {
                if (_Text == null) _Text = GetComponent<Text>();
                return _Text;
            }
        }

        private TextMeshProUGUI TextPro
        {
            get
            {
                if (_TextPro == null) _TextPro = GetComponent<TextMeshProUGUI>();
                return _TextPro;
            }
        }

        protected override BindDataType bindDataType => BindDataType.Object;


        public override void SetData(JSONObject json)
        {
            if (!disabledKey.IsEmpty())
            {
                disabled = invert ? !disabledKey.Get(json).AsBool : disabledKey.Get(json).AsBool;
                if (disabled)
                    Disabled();
                else
                    Enabled();
            }

            base.SetData(json);
        }

        protected override void BindData(JSONObject obj)
        {
            var s = obj[attrKey].Value;
            var c = obj[attrCountKey].Value;
            if (StringTools.IsEmpty(s)) s = "0";
            if (StringTools.IsEmpty(c)) c = "0";
            SetText(string.Format(format, s, c));
        }

        private void SetText(string t)
        {
            if (pro)
                TextPro.text = t;
            else
                Text.text = t;
        }

        private void SetColor(Color c)
        {
            if (pro)
                TextPro.color = c;
            else
                Text.color = c;
        }

        protected override void BindData(bool b)
        {
            if (b)
                Enabled();
            else
                Disabled();
        }

        public void Disabled()
        {
            disabled = true;
            SetColor(disableColor);
            Text.color = disableColor;
        }

        public void Enabled()
        {
            disabled = false;
            SetColor(originColor);
        }
    }
}